import request from '@/utils/request'
import type { ApiResponse } from '@/types/api'

// AI生成页面请求参数
export interface GeneratePagesRequest {
  userMessage: string
  parallelNum: number
}

// Workflow生成完整Book请求参数
export interface GenerateFullBookRequest {
  userMessage: string
}

// Human反馈请求参数
export interface HumanFeedbackRequest {
  userMessage: string
}

// BookVO接口定义
export interface BookVO {
  id: number
  userId: number
  appId: number
  title: string
  uri: string
  cover: string
  description: string
  downloads: number
  isPublic: number
  createTime: string
  updateTime: string
}

// AI生成页面接口
export const generatePages = (data: GeneratePagesRequest): Promise<ApiResponse<string>> => {
  return request({
    url: '/ai/generate/pages',
    method: 'post',
    data
  })
}

// Workflow生成完整Book接口
export const workFlow = (data: GenerateFullBookRequest): Promise<ApiResponse<any>> => {
  return request({
    url: '/ai/workflow',
    method: 'post',
    data
  })
}

// Human反馈接口 - 改为GET方法支持EventSource流式
export const feedback = (userMessage: string): Promise<ApiResponse<any>> => {
  return request({
    url: '/ai/feedback',
    method: 'get',
    params: { feedback: userMessage }
  })
}

// AI写作接口（测试用）
export const aiWrite = (userMessage: string): Promise<ApiResponse<string>> => {
  return request({
    url: '/ai/write',
    method: 'get',
    params: { userMessage }
  })
}

// 获取用户个人书籍列表接口
export const getMyBooks = (appId?: number): Promise<ApiResponse<BookVO[]>> => {
  return request({
    url: '/user/mybooks',
    method: 'get',
    params: appId ? { appId } : {}
  })
}

// 文件下载接口
export const downloadFile = async (filePath: string, bucketName?: string): Promise<Blob> => {
  const params: any = { filePath }
  if (bucketName) {
    params.bucketName = bucketName
  }
  
  try {
    const response = await request({
      url: '/download/file',
      method: 'get',
      params,
      responseType: 'blob',
      timeout: 300000, // 5分钟超时，适合大文件下载
      onDownloadProgress: (progressEvent) => {
        // 可以在这里添加下载进度处理
        if (progressEvent.total) {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
          console.log(`下载进度: ${percentCompleted}%`)
        }
      }
    })
    
    // 检查响应是否是错误信息（JSON格式）
    if (response.type === 'application/json' || response.type.includes('json')) {
      // 如果是JSON响应，说明是错误信息，需要解析并抛出错误
      const text = await response.text()
      try {
        const errorData = JSON.parse(text)
        if (errorData.code && errorData.code !== 0) {
          // 抛出包含错误码和消息的错误
          const error = new Error(errorData.message || '下载失败')
          ;(error as any).code = errorData.code
          ;(error as any).data = errorData.data
          throw error
        }
      } catch (parseError) {
        // 如果解析失败，说明可能不是标准的错误响应
        console.warn('解析错误响应失败:', parseError)
      }
    }
    
    return response
  } catch (error: any) {
    // 如果是我们手动抛出的错误，直接重新抛出
    if (error.code) {
      throw error
    }
    
    // 对于其他类型的错误，包装后抛出
    throw new Error(error.message || '下载请求失败')
  }
}